import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:osg/controllers/http.dart';
import 'package:osg/controllers/my_method.dart';
import 'package:http/http.dart' as http;


 import './h5_upimg.dart' if (dart.library.io) './andino_upimg.dart';



class ImageUploader {
   
  static Future uploadImage() async {
   
     Future<void> muploadImage(File image) async {

        try {
          var request = http.MultipartRequest('POST',
              Uri.parse(Get.find<MyMethod>().myget('upIMG') + '/bbs/upload'));

          request.files.add(
            await http.MultipartFile.fromPath('file', image.path),
          );
          request.headers.addAll({
            'Authorization': Get.find<MyMethod>().myget('token') ?? '',
          });

          var response = await request.send();
          final responseString = await response.stream.bytesToString();
          if (response.statusCode == 200) {
            final jsonData = jsonDecode(responseString);

            return jsonData['data']['url'];
          } else {
            Get.find<HTTPS>().showTost(response.statusCode);
          }
        } catch (e) {
          Get.find<HTTPS>().showTost(e);
        } finally {

        }
      }

    
    if (kIsWeb) {
      final mediaData = await ImagePickerWeb.getImageAsBytes();
      if (mediaData == null) return;

      final uri =
          Uri.parse(Get.find<MyMethod>().myget('upIMG') + '/bbs/upload');
      final request = http.MultipartRequest('POST', uri)
        ..files.add(http.MultipartFile.fromBytes(
          'file',
          mediaData,
          filename: 'upload.jpg',
        ));
      request.headers.addAll({
        'Authorization': Get.find<MyMethod>().myget('token') ?? '',
      });

      Get.find<HTTPS>().loading();
      final response = await request.send();
      final responseData = await http.Response.fromStream(response);
      if (responseData.statusCode == 200) {
        final jsonData = jsonDecode(responseData.body);
        return jsonData['data']['url'];
      } else {
        print('请求失败: ${responseData.statusCode}');
      }

    } else {


      final Rx<File?> selectedImage = Rx<File?>(null);


        try {
          // 选择图片  pickMultipleImages 多选pickImage
          final pickedFile =
               await ImagePicker().pickImage(source: ImageSource.gallery);
             // await ImagePicker().pickMultiImage(limit: 9);

          if (pickedFile == null) return;

          // 更新选中图片
          final imageFile = File(pickedFile.path);
          selectedImage.value = imageFile;

          // 自动触发上传
          Get.find<HTTPS>().loading();
        return  await muploadImage(imageFile);
        } catch (e) {}
    }

    // 处理响应...
  }

  
}
